<route lang="json5">
{
  style: {
    navigationStyle: 'custom',
    navigationBarTitleText: '登录',
  },
}
</route>
<template>
  <view class="login-wrap">
    <!-- <view id="login_box"> -->
    <view class="status_bar">
      <!-- 这里是状态栏 -->
    </view>

    <view class="login-top">
      <!-- <image src="../../static/login-top.png"></image> -->
    </view>
    <view class="logo">
      <image class="logo_img" mode="aspectFit" src="../../static/logo2.png"></image>
      <view class="login_title">欢迎登录</view>
    </view>
    <form class="user_form" style="animation: show 1s 1">
      <view class="form-item">
        <!-- <image src="../../static/icon-people.png" class="form-icon"></image> -->
        <image src="../../static/login/user.png" class="form-icon"></image>
        <view class="input-wrap">
          <input
            v-model="model.user"
            :disabled="loading"
            placeholder-class="phs"
            placeholder="请输入用户名"
            name="input"
            @focus="focusName"
            @blur="blurName"
            :adjust-position="false"
          />
        </view>
        <text
          v-if="model.username && !loading"
          class="cuIcon-close text-gray"
          @click="clearUserName"
        ></text>
      </view>
      <!--  @input="onInput($event, 'password')" -->
      <view class="form-item">
        <image src="../../static/login/pwd.png" class="form-icon"></image>
        <!-- <image src="../../static/icon-lock.png" class="form-icon"></image> -->
        <view class="input-wrap">
          <input
            v-model="model.password"
            :disabled="loading"
            placeholder-class="phs"
            :type="pwd ? 'password' : ''"
            :adjust-position="false"
            placeholder="请输入密码"
            name="input"
          />
        </view>
        <image
          @tap="changeType"
          v-if="!pwd"
          src="../../static/icon-eye.png"
          class="form-icon"
          style="margin-right: 0"
        ></image>
        <image
          @tap="changeType"
          v-else
          src="../../static/icon-eye-no.png"
          class="form-icon"
          style="margin-right: 0"
        ></image>
      </view>
      <view class="form-item">
        <image src="../../static/login/company.png" class="form-icon"></image>
        <!-- <image src="../../static/icon-company.png" class="form-icon"></image> -->
        <!-- <wd-select-picker
            placeholder="请选择公司"
            type="radio"
            prop="tenantId"
            :show-confirm="false"
            v-model="model.tenantId"
            :columns="tenantList"
            @change="onSelectTenant"
            :disabled="tenantList.length == 0"
            customClass="tenant"
            customContentClass="tenant_con"
          /> -->
        <picker
          mode="selector"
          :range="tenantList"
          style="width: 100%; font-size: 35rpx; color: #fff"
          :range-key="pickerKey"
          @change="onSelectTenant"
          :value="activeIndex"
          placeholder="请选择公司"
          :adjust-position="false"
        >
          <view class="title-label">{{ pickerLabel }}</view>
        </picker>
      </view>
    </form>
    <view class="remb">
      <view class="lt" @click="toRemember">
        <view class="is-remb" :class="remember ? 'checked' : 'lt-nochecked'">
          <image src="../../static/icon-logo-remember.png" class="is-remb-icon"></image>
        </view>
        <text>记住账号</text>
      </view>
      <text v-if="false" class="rt" @click="modifyPwd">修改密码</text>
    </view>
    <!-- </view> -->
    <!-- <view style="flex: 1"></view> -->
    <view class="login-submit-item">
      <view class="login-submit" @click="handleSubmit">
        <text class="cuIcon-loading1 cuIconfont-spin" v-if="loading"></text>
        {{ loading ? '正在登录' : '登 录' }}
      </view>
    </view>
    <view class="login-bottom">
      <!-- <image src="../../static/login-bottom.png"></image> -->
    </view>
    <view></view>
  </view>
</template>
<script lang="ts" setup>
import { login, saveClientId, getUserNameList } from '@/service/user';
import { queryPersionTenantList } from '@/service/tenant';
import cache from '@/utils/cache';
import { useUserStore } from '@/stores/user';
import { useMenu } from '@/stores/menu';

const userStore = useUserStore();
const activeIndex = ref(0);
const pickerKey = ref('label');
const pickerLabel = ref('请选择公司');
const menu = useMenu();
const modalH = ref('0');
const pwd = ref(true);
const loading = ref(false);
const model = reactive<{
  username: string;
  password: string;
  tenantId: string;
  user: string;
}>({
  username: '',
  user: '',
  password: '',
  tenantId: '',
});
const preName = ref('');

let redirectUrl: string;
const tenantList = ref([]);
const remember = ref(false);
const toRemember = () => {
  remember.value = !remember.value;
};
const modifyPwd = () => {
  uni.navigateTo({
    url: '/pages/login/password?type=2',
  });
};

const changeType = () => {
  pwd.value = !pwd.value;
};
const focusName = () => {
  preName.value = model.username;
};
const checkChinese = (val) => {
  const reg = new RegExp('[\\u4E00-\\u9FFF]+', 'g');
  return reg.test(val);
};
const dataSource = ref([]);
const blurName = (e) => {
  // if (e.detail.value !== preName.value) {
  //   model.password = '';
  // }
  if (!e.detail.value) return;
  // if (!checkChinese(model.user)) {
  //   model.username = model.user;
  //   getTenantList();
  //   return;
  // }

  const nickname = model.user;
  if (!nickname) return;
  getUserNameList({ nickname }).then((res) => {
    if (res.code != 0) {
      dataSource.value = [];
      return uni.showToast({
        title: `用户不存在`,
        icon: 'none',
      });
    }
    if (res.data.length) {
      // const list = [];
      // res.data.map((item) => {
      //   const obj = {
      //     label: item,
      //     value: item,
      //     labels: nickname,
      //   };
      //   list.push(obj);
      // });
      dataSource.value = res.data;

      // if (dataSource.value.length) {
      if (dataSource.value.length > 1) {
        uni.showActionSheet({
          title: '请选择账号',
          itemList: dataSource.value,
          success: (res) => {
            model.username = dataSource.value[res.tapIndex];
            getTenantList();
          },
          fail: (res) => {
            model.user = '';
            model.username = '';
          },
        });
        // pullDownRef.value?.showPanel();
      } else {
        model.username = dataSource.value[0];
        getTenantList();
      }
      // }
    } else {
      dataSource.value = [];
      model.username = '';
      dataSource.value = [];
      model.tenantId = '';
      tenantList.value = [];
      pickerLabel.value = '请选择公司';
      // model.user = '';
      return uni.showToast({
        title: `用户不存在`,
        icon: 'none',
      });

      // state.ruleForm.username = '';
    }
  });
  // getTenantList();
};
const getTenantList = function () {
  if (!model.username) return;
  queryPersionTenantList({ tenantType: 2, userCode: model.username })
    .then((res) => {
      if (res.code !== 0) {
        pickerLabel.value = '请选择公司';
        model.tenantId = '';
        activeIndex.value = -1;
        uni.showToast({
          title: res.msg || '获取失败',
          icon: 'none',
        });
        tenantList.value = [];
        return;
      }

      tenantList.value = res.data.map((item) => {
        return {
          label: item.simpleName,
          value: item.id,
          code: item.code,
        };
      });
      if (cache.get('tenantId')) {
        model.tenantId = cache.get('tenantId');
        activeIndex.value = tenantList.value.findIndex((item) => item.value === model.tenantId);
        currentTenant.value = tenantList.value.find((item) => item.value === model.tenantId);
        pickerLabel.value = currentTenant.value?.label || '';
      } else {
        model.tenantId = tenantList.value.length ? tenantList.value[0].value : '';
        currentTenant.value = tenantList.value.length ? tenantList.value[0] : {};
        pickerLabel.value = currentTenant.value?.label || '';
        activeIndex.value = 0;
        cache.set('tenantId', model.tenantId);
      }
    })
    .catch(() => {
      pickerLabel.value = '';
      model.tenantId = '';
      cache.set('tenantId', '');
      tenantList.value = [];
    });
};

const formRef = ref();
const clearUserName = () => {
  model.username = '';
  model.user = '';
};
const logging = ref(false);
async function handleSubmit() {
  cache.remove('token');

  // formRef.value
  //   .validate()
  //   .then(({ valid, errors }) => {
  //     if (valid) {
  if (!model.username) {
    return uni.showToast({
      title: '请输入用户名',
      icon: 'none',
    });
  }
  if (!model.password) {
    return uni.showToast({
      title: '请输入密码',
      icon: 'none',
    });
  }
  if (!model.tenantId) {
    return uni.showToast({
      title: '请选择公司',
      icon: 'none',
    });
  }
  if (logging.value) return;
  logging.value = true;
  login(model)
    .then((res) => {
      const { access_token } = res;
      userStore.storeToken(access_token);
      cache.set('tenantId', model.tenantId);
      uni.showToast({
        title: '登录成功',
      });
      cache.set('tenantName', currentTenant.value.label);
      cache.set('tenantCode', currentTenant.value.code);
      cache.set('userCode', model.username);
      if (remember.value) {
        cache.set('remember_username', model.user);
      } else {
        cache.set('remember_username', '');
      }

      cache.set('pwd', model.password);
      userStore.getUser();
      menu.getMenuList();
      uni.hideLoading();

      // #ifdef APP-PLUS
      // 保存clientId
      const clientId = plus.push.getClientInfo().clientid;
      const { userId, username, nickname } = userStore.userInfos.user;
      saveClientId({
        userId,
        username,
        realName: nickname,
        clientId,
      })
        .then(() => {
          // uni.reLaunch({
          //   url: '/pages/index/index',
          //   success() {
          //     if (redirectUrl) {
          //       uni.navigateTo({
          //         url: redirectUrl,
          //       });
          //     }
          //   },
          // });
        })
        .catch((err) => {
          console.log(err);
        })
        .finally(() => {
          uni.reLaunch({
            url: '/pages/index/index',
            success() {
              if (redirectUrl) {
                uni.navigateTo({
                  url: redirectUrl,
                });
              }
            },
          });
        });
      // #endif
      // #ifndef APP-PLUS
      uni.reLaunch({
        url: '/pages/index/index',
        success() {
          if (redirectUrl) {
            uni.navigateTo({
              url: redirectUrl,
            });
          }
        },
      });
      // #endif
      // end
    })
    .finally(() => {
      logging.value = false;
    });
  //   }
  // })
  // .catch((error) => {
  //   console.log(error, 'error');
  //   uni.showToast({
  //     title: error.message,
  //     icon: 'none',
  //   });
  // });
}
const currentTenant = ref<any>({});
const onSelectTenant = function (e) {
  currentTenant.value = tenantList.value[e.detail.value];
  pickerLabel.value = currentTenant.value.label;

  model.tenantId = currentTenant.value.value;
  cache.set('tenantId', model.tenantId);
  cache.set('tenantName', currentTenant.value.label);
  cache.set('tenantCode', currentTenant.value.code);
  // const currentTenant = tenantList.value.find((item) => item.value === value);
  // if (currentTenant) {
  //   cache.set('tenantName', currentTenant.label);
  // }
};

const init = function () {
  // if (cache.get('tenantId')) {
  //   model.tenantId = cache.get('tenantId');
  // }
  // getTenantList();
};
init();
const loginHeight = ref('');
onLoad((options) => {
  redirectUrl = options.redirect || '';
  remember.value = cache.get('remember_username') ? true : false;
  model.user = remember.value ? cache.get('remember_username') : '';
  model.username = remember.value ? cache.get('userCode') : '';
  getTenantList();
});
onShow(() => {
  model.password = '';
});
</script>
<style lang="scss" scoped>
.login-wrap {
  display: flex;
  flex-direction: column;
  height: 100vh;
  min-height: 80vw;
  background-color: white;
  background-image: url('@/static/login/bg.png');
  background-size: cover;
  .status_bar {
    width: 100%;
    height: var(--status-bar-height);

    // background-color: rgb(201,233,255);
    background-image: linear-gradient(to right, rgb(218 237 255), rgb(196 233 255));
  }
}

.tenant {
  width: 100%;
}

.login-top {
  height: 30vw;

  image {
    width: 100vw;
    height: 100%;
  }
}

.login-bottom {
  height: 35vw;

  image {
    width: 100vw;
    height: 100%;
  }
}

:deep() .tenant {
  height: calc(100% + 20rpx);

  .wd-select-picker__cell {
    padding-left: 0;
  }

  .wd-select-picker__value {
    font-size: 34rpx;
    color: #7b7c7d;
  }
}

:deep() .tenant .wd-select-picker__arrow {
  display: none;
}

.logo {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  // margin-top: 18vh;
  .logo_img {
    width: 300rpx;
    height: 120rpx;
    object-fit: cover;
  }
  .login_title {
    margin-top: 32rpx;
    font-size: 36rpx;
    color: rgb(49, 52, 71);
    font-weight: 600;
  }

  // // width: 90vw;
  // // height: 35vw;
  // // width: 640rpx;
  // // height: 270rpx;
  // display: block;

  // // width: 400rpx;
  // // height: 200rpx;
  // width: 600rpx;
  // height: 260rpx;
  // margin: 0 auto 20%;
}

.title-label {
  color: #7b7c7d !important;
}
.user_form {
  margin-top: 200rpx;
  // flex: 1;
  // justify-self: flex-end;
}

form .form-item {
  box-sizing: border-box;
  display: flex;
  align-items: center;
  height: 88rpx;
  padding: 0 20rpx;
  margin: 0 60rpx;
  background: #eff3fd;
  border-radius: 40rpx;
  margin-bottom: 60rpx;
  // margin-bottom: 3vh;
  // line-height: 88rpx;
  // border-bottom: 1rpx solid #afafaf;
}

// .form-item:last-child {
//   margin-bottom: 20rpx !important;
// }

form .form-item text {
  margin-right: 30rpx;
}

form .form-item input {
  flex: 1;
  font-size: 35rpx !important;
  color: #7b7c7d !important;
  background-color: #eff3fd;
}

.phs {
  margin-top: 2px;
  color: #7b7c7d !important;

  // z-index: 999;
}

:deep() .uni-input-input:-internal-autofill-selected {
  margin-top: 2px;
  box-shadow: inset 0 60px 0 #fff !important;
}

button {
  flex: 1;
}

.input-wrap {
  display: flex;
  flex: 1;
  flex-direction: column;
  justify-content: center;
}

.cuIcon-people,
.cuIcon-lock,
.cuIcon-attentionfill,
.cuIcon-attention,
.cuIcon-roundclose {
  font-size: 40rpx;
}

.remb {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin: 0rpx 120rpx 0 140rpx;
  font-size: 32rpx;
  line-height: 60rpx;
  color: #000;
}

.remb {
  text {
    font-size: 28rpx;
    color: rgb(35, 169, 255);
  }
  .lt {
    display: flex;
    align-items: center;
    line-height: 60rpx;
    color: #000;
  }
}

.is-remb {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32rpx;
  height: 32rpx;
  margin-right: 20rpx;
  overflow: hidden;
  border-radius: 50%;
  box-sizing: border-box;
  padding: 5rpx;

  .is-remb-icon {
    width: 25rpx;
    height: 25rpx;
  }
}

.is-remb.checked {
  // background: #fff url(../../static/checked.svg) no-repeat center center;
  // background-size: 80% 80%;
  background-color: rgb(35, 169, 255);
  border: 1px solid rgb(35, 169, 255);
}

.lt-nochecked {
  background-color: white;
  border: 1px solid rgb(35, 169, 255);
}

.login-submit-item {
  // padding: 20% 0 0%;
  padding: 80rpx 0 0;

  .login-submit {
    width: 60%;
    height: 85rpx;
    margin: 0 auto;
    font-size: 40rpx;

    // display: flex;
    // align-items: center;
    // justify-content: center;
    line-height: 85rpx;
    color: white;
    text-align: center;

    // background-color: #0081ff;
    background-color: rgb(35, 169, 255);
    border-radius: 40rpx;
  }
}

.form-icon {
  width: 46rpx;
  height: 46rpx;
  margin-right: 30rpx;
}
@media screen and (min-width: 480px) {
  // .login-wrap {
  //   background-image: url('@/static/login/bg_big.png');
  // }
  .login-top {
    height: 40vw;
  }
}
</style>
